package com.kt.emall.search.thread;

import java.util.concurrent.*;

/**
 * @program: e-mall
 * @description: 线程测试
 * @author: KamTang
 * @create: 2021-10-18 20:53
 **/
public class ThreadTest {
    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main......start...");
        CompletableFuture<Object> future01 = CompletableFuture.supplyAsync(() -> {
            System.out.println("future01线程");
            return "Hello";
        }, executor);

        CompletableFuture<Object> future02 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);
                System.out.println("future02线程");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "World";
        });

        CompletableFuture<Object> future03 = CompletableFuture.supplyAsync(() -> {
            System.out.println("future03线程");
            return "你好";
        });

        CompletableFuture<Object> anyOf = CompletableFuture.anyOf(future01, future02, future03);
        System.out.println("main......end..." + anyOf.get());
    }

    public void thread(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main......start...");
        /**
         * 1)、继承Thread
         * 2)、实现Runnable
         * 3)、实现Callable接口 + FutureTask（可以拿到返回结果，可以处理异常）
         * 4)、线程池
         */
        ThreadPoolExecutor executor = new ThreadPoolExecutor(5,
                200,
                10,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(100000),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

//        Executors.newCachedThreadPool() core是0，所有都可回收
//        Executors.newFixedThreadPool() 固定大小，core=max；都不可回收
//        Executors.newScheduledThreadPool() 定时任务的线程池
//        Executors.newSingleThreadExecutor() 单线程的线程池，后台从队列里面获取任务，挨个执行
        System.out.println("main......end...");
    }

    public static class Thread01 extends Thread {
        @Override
        public void run() {
            System.out.println("当前线程：" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果：" + i);
        }
    }

    public static class Runable01 implements Runnable {
        @Override
        public void run() {
            System.out.println("当前线程：" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果：" + i);
        }
    }

    public static class Callable01 implements Callable<Integer> {

        @Override
        public Integer call() throws Exception {
            System.out.println("当前线程：" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果：" + i);
            return i;
        }
    }
}
